import * as vscode from 'vscode'
import { RecordService } from '../services/recordService'
import { CommentService } from '../services/commentService'
import { showEditForm } from '../ui/forms/editForm'
import RecordViewProvider from '../providers/recordViewProvider'

export class EditCommands {
  constructor(private recordService: RecordService, private commentService: CommentService, private recordViewProvider: RecordViewProvider) {}

  // 编辑记录命令
  async editRecord(recordId: number): Promise<void> {
    const record = this.recordService.findRecord(recordId)
    if (!record) {
      vscode.window.showErrorMessage('记录不存在')
      return
    }

    const context = {
      filePath: record.filePath,
      codeSnippet: record.codeSnippet,
      lineRange: record.lineRange
    }

    // 包含标签的现有数据
    const existingData = {
      problem: record.problem,
      solution: record.solution,
      tags: record.tags || [] // 新增：传递现有标签
    }

    try {
      const updatedData = await showEditForm(context, existingData)

      if (updatedData && updatedData.problem && updatedData.solution) {
        // 更新记录，包含标签
        const updatePayload: any = {
          problem: updatedData.problem,
          solution: updatedData.solution
        }

        // 如果表单返回了标签数据，包含在更新中
        if (updatedData.tags !== undefined) {
          updatePayload.tags = updatedData.tags
        }

        const updatedRecord = await this.recordService.updateRecord(recordId, updatePayload)

        if (updatedRecord) {
          await this.commentService.updateRecordComment(recordId, updatedData.problem, record.filePath)
          this.recordViewProvider.updateRecords(this.recordService.getWorkspaceRecords())
          vscode.window.showInformationMessage('记录已更新，文件已自动保存!')
        }
      }
    } catch (error) {
      console.error('编辑记录失败:', error)
      vscode.window.showErrorMessage('编辑失败: ' + error)
    }
  }
}
